// 简单封装请求api, 处理返回报文
import service from './service'

const request = (options) => {
  return new Promise((resolve, reject) => {
    service(options).then(response => {
      const { status, data: result } = response
      if (status === 200) {
        const { code, data, msg } = result

        if (code === '1000') {
          resolve(data)
        } else if (code === '4003' || code === '4002') { // 登录提示
          reject(new Error('请先登录'))
        } else {
          reject(new Error(msg))
        }
      } else {
        reject(new Error('网络异常，请稍后再试'))
      }
    }).catch(err => {
      reject(err)
    })
  })
}

const api = request

api.get = function (url, options) {
  if (typeof url === 'string') {
    options = options || {}
    options.url = url
  } else {
    options = url
  }
  options.method = 'GET'
  return request(options)
}

api.post = function (url, options) {
  if (typeof url === 'string') {
    options = options || {}
    options.url = url
  } else {
    options = url
  }
  options.method = 'POST'
  return request(options)
}

api.service = service

export default api
